package com.kungfuhacking.wristbandpro.chat.presenter;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.audio.UPlayer;
import com.kungfuhacking.wristbandpro.base.Mapplication;
import com.kungfuhacking.wristbandpro.chat.activity.ChatActivity;
//import com.kungfuhacking.wristbandpro.chat.bean.ShowTimeBean;
import com.kungfuhacking.wristbandpro.database.DatabaseManager;
import com.kungfuhacking.wristbandpro.mqtt.MqttConstant;
import com.kungfuhacking.wristbandpro.mqtt.bean.MessageBean;
import com.kungfuhacking.wristbandpro.utils.AbDateUtil;
import com.kungfuhacking.wristbandpro.utils.CommonUtils;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.DensityUtil;

import java.lang.reflect.Field;
import java.util.List;

import static com.kungfuhacking.wristbandpro.R.id.tv_content;

/**
 * 聊天内容页面的adapter
 * Created by Aaron on 15/12/23.
 */
public class ChatAdapter extends BaseAdapter {

    private String TAG = getClass().getSimpleName();

    private Context ctx;
    private List<MessageBean> mb;
    //    private final int TYPECOUNT = 2;
    private Mapplication mApplication;
    boolean isPlaying;
    private int LEFT = 0;
    private int RIGHT = 1;
    private UPlayer uPlayer;
    private SharedPreferences sp;
    private String currentPlayingVideoUrl = "";//当前播放的录音文件的路径
    //    private AnimationDrawable lastAnimation;
    private ImageView playingVoiceView;
    private AnimationDrawable playingAnimation;
    private int lastSide = -1;
    //    private long currentShowTime;
//    private ShowTimeBean showTimeBean = new ShowTimeBean();
//    private boolean isFirstIn = true;

    public ChatAdapter(List<MessageBean> messages, Context ctx) {
        this.mb = messages;
        this.ctx = ctx;
        this.mApplication = (Mapplication) ctx.getApplicationContext();
        sp = ctx.getSharedPreferences(Constant.CONFIG, Context.MODE_PRIVATE);

    }

    @Override
    public int getCount() {


//        if (currentShowTime == 0 && mb.size() > 0) {
////            isFirstIn = false;
//            currentShowTime = mb.get(mb.size() - 1).sendDate;
//        }

        return mb.size();
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        //根据发送者的id 判断发消息的是否是本人
        return sp.getString(MqttConstant.USERID, "").equals(mb.get(position).sendId) ? RIGHT : LEFT;
    }

    private int imageResource = -1;

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder mHolder;

        if (getItemViewType(position) == LEFT) {

            if (convertView == null) {
                mHolder = new ViewHolder();
                convertView = View.inflate(ctx, R.layout.item_chat_left, null);
                mHolder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                mHolder.tv_content = (TextView) convertView.findViewById(tv_content);
                mHolder.iv_head_pic = (SimpleDraweeView) convertView.findViewById(R.id.iv_head_pic);
                mHolder.rl_record = (LinearLayout) convertView.findViewById(R.id.rl_record);
                mHolder.rl_total = (RelativeLayout) convertView.findViewById(R.id.rl_total);
                mHolder.iv_voice = (ImageView) convertView.findViewById(R.id.iv_voice);
                mHolder.iv_isListened = (ImageView) convertView.findViewById(R.id.iv_isListened);
                mHolder.tv_second = (TextView) convertView.findViewById(R.id.tv_second);
                mHolder.tv_remaind = (TextView) convertView.findViewById(R.id.tv_remaind);
                mHolder.tv_send_name = (TextView) convertView.findViewById(R.id.tv_send_name);
                mHolder.iv_photo = (ImageView) convertView.findViewById(R.id.iv_photo);

                convertView.setTag(mHolder);

            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }

        } else {

            if (convertView == null) {
                mHolder = new ViewHolder();
                convertView = View.inflate(ctx, R.layout.item_chat_right, null);
                mHolder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                mHolder.tv_content = (TextView) convertView.findViewById(tv_content);
                mHolder.iv_head_pic = (SimpleDraweeView) convertView.findViewById(R.id.iv_head_pic);
                mHolder.rl_record = (LinearLayout) convertView.findViewById(R.id.rl_record);
                mHolder.rl_total = (RelativeLayout) convertView.findViewById(R.id.rl_total);
                mHolder.iv_voice = (ImageView) convertView.findViewById(R.id.iv_voice);
                mHolder.iv_isListened = (ImageView) convertView.findViewById(R.id.iv_isListened);
                mHolder.tv_second = (TextView) convertView.findViewById(R.id.tv_second);
                mHolder.tv_remaind = (TextView) convertView.findViewById(R.id.tv_remaind);
                mHolder.iv_photo = (ImageView) convertView.findViewById(R.id.iv_photo);
                mHolder.tv_sending = (ImageView) convertView.findViewById(R.id.tv_sending);

                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }

        }

        //*******************************   设置数据   *******************************//

        if (mb == null || mb.get(position) == null)
            return convertView;

        //防止复用出错
        if (mHolder.tv_send_name != null)
            mHolder.tv_send_name.setVisibility(View.GONE);

        if (mHolder.tv_sending != null)
            mHolder.tv_sending.setVisibility(View.GONE);

        //防止复用时混乱,先置空 一定要置空,否则报错!!!!!!!!
        mHolder.tv_content.setText("");

        //防止错乱 先隐藏
        mHolder.tv_time.setVisibility(View.GONE);
//        //设置日期
//        setDateInfo(position, mHolder);

        //如果是群聊,并且发送者不是本人,则显示昵称
//        if (CommonUtils.isGroupChat(mb.get(position).channelId)
//                && !mb.get(position).sendId.equals(sp.getString(MqttConstant.USERID, ""))) {
            if (mHolder.tv_send_name != null) {
                mHolder.tv_send_name.setVisibility(View.VISIBLE);
                mHolder.tv_send_name.setText(mb.get(position).sendName);
            }
//        } else {
//            if (mHolder.tv_send_name != null)
//                mHolder.tv_send_name.setVisibility(View.GONE);
//        }

        if (mb.get(position).sendId.equals(sp.getString(MqttConstant.USERID, ""))) {
            //是本人发送的消息
            switch (mb.get(position).isReach) {

                case MqttConstant.MESSAGE_SEND_FAIL:
                    if (mHolder.tv_sending != null) {
                        mHolder.tv_sending.setVisibility(View.VISIBLE);
                        mHolder.tv_sending.setImageResource(R.mipmap.ic_sending_fail);
                        mHolder.tv_sending.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                resendMsg(mb.get(position));
                            }
                        });
                    }

                    break;

                case MqttConstant.MESSAGE_SENDING:
                    if (mHolder.tv_sending != null) {

                        mHolder.tv_sending.setVisibility(View.VISIBLE);
                        mHolder.tv_sending.setImageResource(R.mipmap.ic_sending);
                        mHolder.tv_sending.setOnClickListener(null);
                    }
                    break;

                default:
                    if (mHolder.tv_sending != null)
                        mHolder.tv_sending.setOnClickListener(null);
                    break;
            }

        }

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                DensityUtil.dip2px(ctx, 20), DensityUtil.dip2px(ctx, 20));
        lp.addRule(RelativeLayout.CENTER_VERTICAL);//在父控件中垂直居中

        switch (mb.get(position).messageType) {

            case MqttConstant.MQTTMESSAGETEXT://纯文本
                //隐藏record 和 图片 布局 显示文本布局
                mHolder.tv_remaind.setVisibility(View.GONE);
                mHolder.rl_record.setVisibility(View.GONE);
                mHolder.iv_photo.setVisibility(View.GONE);
                mHolder.tv_content.setVisibility(View.VISIBLE);
                mHolder.rl_total.setVisibility(View.VISIBLE);
                //设置聊天内容
                setChatText(mb.get(position).content, mHolder);
//                RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.LEFT_OF, tv_content);
                if (mHolder.tv_sending != null)
                    mHolder.tv_sending.setLayoutParams(lp);

//                Log.d(TAG, "当前屏幕的宽度 width:" + CommonUtils.getScreenSize(ctx)[0] + ",heigh:" + CommonUtils.getScreenSize(ctx)[1]);
//                mHolder.tv_content.setMaxWidth();

                break;

            case MqttConstant.MQTTMESSAGEPHOTO://图片
                //隐藏record 和 文本 布局 显示图片布局
                mHolder.tv_remaind.setVisibility(View.GONE);
                mHolder.rl_record.setVisibility(View.GONE);
                mHolder.iv_photo.setVisibility(View.VISIBLE);
                mHolder.tv_content.setVisibility(View.GONE);
                mHolder.rl_total.setVisibility(View.VISIBLE);

                lp.addRule(RelativeLayout.LEFT_OF, R.id.iv_photo);
                if (mHolder.tv_sending != null)
                    mHolder.tv_sending.setLayoutParams(lp);

                //加载图片
                loadImage(position, mHolder);

                break;

            case MqttConstant.MQTTMESSAGEVOICE://音频

                //隐藏record 和 文本 布局 显示图片布局
                mHolder.tv_remaind.setVisibility(View.GONE);
                mHolder.rl_record.setVisibility(View.VISIBLE);
                mHolder.iv_photo.setVisibility(View.GONE);
                mHolder.tv_content.setVisibility(View.GONE);
                mHolder.rl_total.setVisibility(View.VISIBLE);

                lp.addRule(RelativeLayout.LEFT_OF, R.id.rl_record);
                if (mHolder.tv_sending != null)
                    mHolder.tv_sending.setLayoutParams(lp);

                setRecordData(position, mHolder);

                break;

//            case MqttConstant.MQTTMESSAGENOTICE://创建群 加人,删人,修改群昵称
//
//                //隐藏record 和 图片 布局 显示文本布局
//                mHolder.rl_record.setVisibility(View.GONE);
//                mHolder.iv_photo.setVisibility(View.GONE);
//                mHolder.tv_content.setVisibility(View.GONE);
//                mHolder.rl_total.setVisibility(View.GONE);
//                mHolder.tv_remaind.setVisibility(View.VISIBLE);
//
//                String content = mb.get(position).content;
//
//                //设置聊天内容
//                if (sp.getString(MqttConstant.USERID, "").equals(mb.get(position).sendId))
//                    content = mb.get(position).content.replaceFirst(sp.getString(Constant.NICKNAME, ""), "您");
//
//                mHolder.tv_remaind.setText(content);
//                mHolder.tv_time.setVisibility(View.VISIBLE);
//                mHolder.tv_time.setText(AbDateUtil.getChatDate(mb.get(position).sendDate));
//
//                break;

        }

        if (mb.get(position).channelId != null && mb.get(position).channelId.startsWith(MqttConstant.START_S)) {
//            Log.d(TAG, "  ----  加载本地小头像  ---- ");
            mHolder.iv_head_pic.setImageResource(R.mipmap.ic_logo_small);
        } else {
//            Log.d(TAG, "  ----  加载网络小头像  ---- " + mb.get(position).sendPic);
            //设置头像
            mHolder.iv_head_pic.setImageURI(Uri.parse(getItemViewType(position) == LEFT ? (TextUtils.isEmpty(mb.get(position).sendPic)? "" :mb.get(position).sendPic ): sp.getString(Constant.USER_IMG, "")));
        }

        final ImageView iv_play_voice = mHolder.iv_voice;

        if (mb.get(position).showTime) {
            mHolder.tv_time.setVisibility(View.VISIBLE);
            mHolder.tv_time.setText(AbDateUtil.getChatDate(mb.get(position).sendDate));
        } else {
            mHolder.tv_time.setVisibility(View.GONE);
        }

        //大于3分钟 ,显示时间
        if (position > 1) {
            if (mb.get(position).sendDate - mb.get(position - 1).sendDate > 3 * 60 * 1000) {
                mHolder.tv_time.setVisibility(View.VISIBLE);
                mHolder.tv_time.setText(AbDateUtil.getChatDate(mb.get(position).sendDate));
            }
        }

//        }
//        mHolder.tv_time.setVisibility(mb.get(position).showTime ? View.VISIBLE : View.GONE);
//        if ((currentShowTime - mb.get(position).sendDate) >= 3 * 60 * 1000) {
//            mHolder.tv_time.setVisibility(View.VISIBLE);
//            currentShowTime = mb.get(position).sendDate;
////            Log.d(TAG, "显示时间 ：" + currentShowTime);
//            mHolder.tv_time.setText(AbDateUtil.getChatDate(mb.get(position).sendDate));
//        } else {
//            mHolder.tv_time.setVisibility(View.GONE);
//        }

        final ImageView iv = mHolder.iv_isListened;

        //点击播放录音文件
        mHolder.iv_voice.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                Log.d(TAG, "是否正在播放中 : " + isPlaying + ",当前播放的路径: " + currentPlayingVideoUrl);
                //播放音频文件
                playVideo(position, iv, iv_play_voice);

            }

        });

        mHolder.iv_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.d(TAG, " 聊天图片的点击事件 onClickListener ");
                if (ctx instanceof ChatActivity) {
                    ChatActivity chatActivity = (ChatActivity) ctx;
                    chatActivity.showPicDetail(mb.get(position).content);
                }

            }
        });

        return convertView;
    }

    /**
     * 重新发送聊天消息
     *
     * @param messageBean
     */
    private void resendMsg(MessageBean messageBean) {

        ChatActivity cha = (ChatActivity) ctx;
        //TODO 删除该条数据,修改发送日期跟发送状态
        DatabaseManager.getInstance().deleteData(ctx, messageBean);
        mb.remove(messageBean);
        messageBean.isReach = 1;
        messageBean.sendDate = System.currentTimeMillis();
        cha.sendMsg(messageBean);

    }

//    /**
//     * 设置日期
//     *
//     * @param position
//     * @param mHolder
//     */
//    private void setDateInfo(int position, ViewHolder mHolder) {
//        if (position % 5 == 0) {
//            mHolder.tv_time.setVisibility(View.VISIBLE);
////            Log.d(TAG, "发送的消息的时间戳:" + sendDate + ",当地时间:" + new Date(sendDate).toLocaleString());
//            mHolder.tv_time.setText(AbDateUtil.getChatDate(mb.get(position).sendDate));
//        } else
//            mHolder.tv_time.setVisibility(View.GONE);
//    }

    private void playVideo(int position, ImageView iv, ImageView iv_play_voice) {
        //判断有没有播放过,如果未播放过 则把播放状态设置为已播放过
        if (mb.get(position).isListener == MqttConstant.UNLISTENER) {
//            //打开数据库
//            DatabaseManager.getInstance().init(ctx.getApplicationContext());
            DatabaseManager.getInstance().updateListenerStatus(ctx, new String[]{MqttConstant.LISTENERED + "", mb.get(position).channelId,
                    sp.getString(MqttConstant.USERID, ""), mb.get(position).sendId, mb.get(position).sendDate + ""});

            DatabaseManager.getInstance().updateTopicListenerStatus(ctx, new String[]{MqttConstant.LISTENERED + "", mb.get(position).channelId,
                    sp.getString(MqttConstant.USERID, ""), mb.get(position).sendId, mb.get(position).sendDate + ""});

            mb.get(position).isListener = MqttConstant.LISTENERED;
            iv.setVisibility(View.INVISIBLE);
        }

        if (isPlaying) {
            //播放中,判断当前是否正在播放当前的录音文件, 如果是当前的录音文件 则停止播放,
            // 如果不是当前的录音文件,则停止播放,并且播放点击的录音文件
            if (uPlayer != null) {

                uPlayer.stop();
                playingAnimation.stop();
                if (playingVoiceView != null)
                    playingVoiceView.setImageResource(
                            lastSide == RIGHT
                                    ? R.mipmap.ic_voice_three_right : R.mipmap.ic_voice_three_left);

            }

            if (!TextUtils.isEmpty(currentPlayingVideoUrl) &&
                    !mb.get(position).content.equals(currentPlayingVideoUrl)) {

                if (h != null)
                    h.removeCallbacksAndMessages(null);

                //播放点击的录音文件
                startPlay(iv_play_voice, mb.get(position));
            }

        } else {
            //未播放, 开始播放
            startPlay(iv_play_voice, mb.get(position));
        }

        lastSide = sp.getString(MqttConstant.USERID, "").equals(mb.get(position).sendId) ? RIGHT : LEFT;
    }

    /**
     * 停止播放语音文件
     */
    public void stopPlayVideo() {

        if (isPlaying && uPlayer != null && playingAnimation != null) {
            uPlayer.stop();
            playingAnimation.stop();
            currentPlayingVideoUrl = "";
            notifyDataSetChanged();
        }

    }

    /**
     * 设置录音文件
     *
     * @param position
     * @param mHolder
     */
    private void setRecordData(int position, ViewHolder mHolder) {

        mHolder.iv_isListened.setVisibility(View.INVISIBLE);//防止复用出错

        if (currentPlayingVideoUrl.equals(mb.get(position).content)) {
            //如果当前播放的是该条目,则播放
            mHolder.iv_voice.setImageResource(sp.getString(MqttConstant.USERID, "").equals(mb.get(position).sendId) ?
                    R.drawable.voice_play_right : R.drawable.voice_play_left);

            playingAnimation = (AnimationDrawable) mHolder.iv_voice.getDrawable();
            playingAnimation.start();

        } else {
            mHolder.iv_voice.setImageResource(sp.getString(MqttConstant.USERID, "").equals(mb.get(position).sendId)
                    ? R.mipmap.ic_voice_three_right : R.mipmap.ic_voice_three_left);
        }

        int voiceLength = (int) mb.get(position).voiceLength;

        if (voiceLength < 1) voiceLength = 1;
        if (voiceLength > 60) voiceLength = 60;

        mHolder.tv_second.setText(voiceLength + "''");

        //设置音频的条目的长度
        int maxLength = CommonUtils.getScreenSize(ctx)[0] - DensityUtil.dip2px(ctx, 200); //计算出音频文件所允许的最大长度
        int minLength = DensityUtil.dip2px(ctx, 60);
        int base = (maxLength - minLength) / 60;

        //计算出当前的长度
        int showLength = minLength + base * voiceLength;

        LinearLayout.LayoutParams rl = new LinearLayout.LayoutParams(showLength, DensityUtil.dip2px(ctx, 45));

        //设置params参数
        if (getItemViewType(position) == LEFT) {
            rl.setMargins(DensityUtil.dip2px(ctx, 5), 0, 0, 0);

            mHolder.iv_voice.setPadding(DensityUtil.dip2px(ctx, 12), DensityUtil.dip2px(ctx, 12),
                    showLength - DensityUtil.dip2px(ctx, 50), DensityUtil.dip2px(ctx, 12));

            if (mb.get(position).isListener == MqttConstant.UNLISTENER) {//没有听过
                mHolder.iv_isListened.setVisibility(View.VISIBLE);
            } else {//已经听过了
                mHolder.iv_isListened.setVisibility(View.INVISIBLE);
            }

        } else {
            rl.setMargins(0, 0, DensityUtil.dip2px(ctx, 5), 0);
            mHolder.iv_voice.setPadding(showLength - DensityUtil.dip2px(ctx, 50), DensityUtil.dip2px(ctx, 12),
                    DensityUtil.dip2px(ctx, 12), DensityUtil.dip2px(ctx, 12));
        }

        mHolder.iv_voice.setLayoutParams(rl);

    }

    private Handler h;

    /**
     * 开始播放录音文件
     *
     * @param
     */
    private void startPlay(final ImageView iv_play_voice, final MessageBean mb) {

        iv_play_voice.setImageResource(sp.getString(MqttConstant.USERID, "").equals(mb.sendId) ?
                R.drawable.voice_play_right : R.drawable.voice_play_left);

        playingAnimation = (AnimationDrawable) iv_play_voice.getDrawable();
        playingAnimation.start(); //开始播放

        h = new Handler();

        h.postDelayed(new Runnable() {
            @Override
            public void run() {

                if (playingAnimation != null)
                    playingAnimation.stop();//停止播放
                currentPlayingVideoUrl = "";
                ((ChatActivity) ctx).fush();

            }   //延迟1秒改变状态
        }, (int) (mb.voiceLength * 1000 + 1000));

        uPlayer = new UPlayer(mb.content);
        uPlayer.start();

        playingVoiceView = iv_play_voice;
        currentPlayingVideoUrl = mb.content;

        isPlaying = true;
    }

    public void setIsPlaying(boolean isPlaying) {
        this.isPlaying = isPlaying;
    }

    private void loadImage(int position, ViewHolder mHolder) {

        int maxLength = CommonUtils.getScreenSize(ctx)[0] / 2 - DensityUtil.dip2px(ctx, 100); //计算出图片的最大宽度, 高度与之类似

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        //聊天发送的时候 content 为 字节码,strContent 为图片的路径;
        //查询历史记录的时候 content 为图片路径.(数据库中未存储strContent字段)
//        Log.d(TAG, "adapter加载的图片路径:" + mb.get(position).content);
        BitmapFactory.decodeFile(mb.get(position).content, opts);

        Log.e(TAG, "图片的宽 : " + opts.outWidth + ",图片的高 : " + opts.outHeight);

        double scale = 0;
        //先判断图片的偏宽的 还是偏长的
        if (opts.outWidth > opts.outHeight) //图片偏宽的
            scale = (double) opts.outWidth / (double) maxLength;//获得缩放比例
        else //图片偏长的
            scale = (double) opts.outHeight / (double) maxLength;

        if (scale < 1) //如果实际大小小于给定尺寸,则设置缩放比例为1
            scale = 1;

        opts.inSampleSize = (scale == 1 ? 1 : (int) (scale + 1));
        Log.e(TAG, " adapter 里面 opts.inSampleSize :" + opts.inSampleSize + ", maxLength : " + maxLength);

        opts.inJustDecodeBounds = false;
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        mHolder.iv_photo.setImageBitmap(BitmapFactory.decodeFile(mb.get(position).content, opts));
//      Log.d("TAG, "图片的尺寸width:" + opts.outWidth + ",height:" + opts.outHeight);

    }

    private static class ViewHolder {
        TextView tv_time;
        SimpleDraweeView iv_head_pic;
        TextView tv_content;
        LinearLayout rl_record;
        ImageView iv_voice;
        TextView tv_second;
        ImageView iv_isListened;
        ImageView iv_photo;
        TextView tv_remaind;
        TextView tv_send_name;
        RelativeLayout rl_total;
        ImageView tv_sending;
    }

    /**
     * 设置聊天内容
     *
     * @param contentstr
     * @param mHolder
     */
    private void setChatText(String contentstr, ViewHolder mHolder) {

        //检查是否表情内容
        if (CommonUtils.isContainEmo(contentstr)) {

//            Log.d(TAG, " ************* 包含表情 ************");
            List<String> emoList = CommonUtils.getEmoList(contentstr); //获取到!类似!表情的[XX] 集合

            Field field = null;

            int startIndex = 0;
            int endIndex = 0;

            for (int i = 0; i < emoList.size(); i++) {//依次提取类似表情的字段 [XX]

                String emoTxt = emoList.get(i);//提取出来的 类似 表情字符串

//                Log.d(TAG, " 提取出来的 类似 表情字符串 emoTxt : " + emoTxt);
                if (mApplication.getEmoMap() != null && mApplication.getEmoMap().containsKey(emoTxt)) {
                    //该类似表情内容 确实是表情内容
                    //根据表情的code获得表情的图片名称
                    String imageName = mApplication.getEmoMap().get(emoTxt);
//                    //根据图片名称获取图片的资源id
                    try {
                        field = R.drawable.class.getDeclaredField(imageName);
                        imageResource = Integer.parseInt(field.get(null).toString());//通过上面匹配得到的字符串来生成图片资源id
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    endIndex = contentstr.indexOf(emoTxt, startIndex);
                    //截取 纯字内容
                    String substring = contentstr.substring(startIndex, endIndex);
//                    Log.d(TAG, "截取的内容:" + substring);
                    mHolder.tv_content.append(substring);

                    if (imageResource != -1) {

                        Drawable d = ctx.getResources().getDrawable(imageResource);
                        d.setBounds(0, 0, 80, 80);//设置表情图片的显示大小
                        ImageSpan imageSpan = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
                        //  创建一个SpannableString对象，以便插入用ImageSpan对象封装的图像
                        SpannableString spannableEmo = new SpannableString(emoTxt);//参数为图片的正则 (例如[得意])
                        //  用ImageSpan对象替换 regxName
                        spannableEmo.setSpan(imageSpan, 0, spannableEmo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        mHolder.tv_content.append(spannableEmo);

                    }

                    startIndex = mHolder.tv_content.getText().toString().length();

                    if (i == emoList.size() - 1)
                        //最后一个表情
                        mHolder.tv_content.append(contentstr.substring(startIndex, contentstr.length()));

                } else {
                    //该类似表情内容 不是表情内容
                    endIndex = contentstr.indexOf(emoTxt, startIndex) + emoTxt.length();
                    //截取 纯字内容
                    String substring = contentstr.substring(startIndex, endIndex);
                    mHolder.tv_content.append(substring);
                    startIndex = mHolder.tv_content.getText().toString().length();

                    if (i == emoList.size() - 1)
                        //最后一个类似表情
                        mHolder.tv_content.append(contentstr.substring(startIndex, contentstr.length()));

                }

            }

        } else {
            mHolder.tv_content.setText(contentstr);
        }
    }

}
